package com.zgc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgc.common.aop.CheckPermission;
import com.zgc.common.R;
import com.zgc.dto.EmployeeDto;
import com.zgc.entity.*;
import com.zgc.service.EmpRoleService;
import com.zgc.service.EmployeeService;
import com.zgc.service.RoleService;
import com.zgc.util.MailSenderUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmpRoleService empRoleService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }
    @Autowired
    private MailSenderUtil util;
    @Autowired
    private RoleService roleService;



    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    @CheckPermission
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee) throws MessagingException {
        log.info("新增员工，员工信息：{}",employee.toString());
        String psd=employee.getPassword();
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));

        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //获得当前登录用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        employeeService.save(employee);
        String toUser = employee.getEmail();
        String title="用户系统个人账户信息";
        String body="亲爱的"+employee.getName()+"用户您的用户名："+employee.getUsername()+"，密码是: "+psd+" ，请注意查收";
        util.sendMail(toUser,title,body);
        return R.success("新增员工成功,已发送信息到员工邮箱中");
    }
    /**
     * 员工信息分页查询
     * @param page 当前查询页码
     * @param pageSize 每页展示记录数
     * @param name 员工姓名 - 可选参数
     * @return
     */
    /**
     * 员工信息分页查询
     * @param page 当前查询页码
     * @param pageSize 每页展示记录数
     * @param name 员工姓名 - 可选参数
     * @return
     */
    @GetMapping("/page")
    @CheckPermission //配置权限 加注解---------==========
    public R<Page> page(int page,int pageSize,String name){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);
        //构造分页构造器
        Page<Employee> pageInfo = new Page(page,pageSize);
        Page<EmployeeDto> employeeDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo,queryWrapper);
        BeanUtils.copyProperties(pageInfo,employeeDtoPage,"records");
        List<Employee> records = pageInfo.getRecords();
        List<EmployeeDto> list = records.stream().map((item) -> {
                    EmployeeDto employeeDto = new EmployeeDto();
                    BeanUtils.copyProperties(item, employeeDto);
                    Long empid = item.getId();
                    //根据empid查询empRole这张表
                    LambdaQueryWrapper<EmpRole> empRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    empRoleLambdaQueryWrapper.eq(StringUtils.isNotEmpty(String.valueOf(empid)), EmpRole::getEmpId, empid);
                    EmpRole empRole = empRoleService.getOne(empRoleLambdaQueryWrapper);
                    if(null !=empRole) {
                        String roleid = empRole.getRoleId();
                        //查询role表
                        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper();
                        roleLambdaQueryWrapper.eq(StringUtils.isNotEmpty(roleid), Role::getId, roleid);
                        Role role = roleService.getOne(roleLambdaQueryWrapper);
                        employeeDto.setRoles(role.getName());

                    }
                    return employeeDto;
                  }).collect(Collectors.toList());
        employeeDtoPage.setRecords(list);
        return R.success(employeeDtoPage);
    }
    /**
     * 根据id修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    @CheckPermission
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee) throws MessagingException {
        log.info(employee.toString());
        Long empId = (Long)request.getSession().getAttribute("employee");
        String psd=employee.getPassword();
        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(empId);
        employeeService.updateById(employee);
        String toUser = employee.getEmail();
        String title="用户系统个人账户信息";
        String body="亲爱的"+employee.getName()+"用户,您的账户信息已修改，您的用户名："+employee.getUsername()+"，密码:"+psd+"，请注意查收";
        util.sendMail(toUser,title,body);
        return R.success("员工信息修改成功,已发送信息到员工邮箱中");
    }
    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @CheckPermission
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }




}
